package com.fuint.common.util;

import cn.hutool.json.JSONUtil;
import com.fuint.utils.syb.SybWxPayDTO;
import com.fuint.utils.syb.SybPayUtils;
import com.fuint.utils.syb.SybUtil;
import com.fuint.utils.syb.SybYunPayDTO;
import org.springframework.http.*;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.TreeMap;

import static com.fuint.utils.syb.SybConstants.*;
import static com.fuint.utils.syb.SybConstants.PAY_PATH;

public class PayUtil {
    public static Map<String, String> yunPay(SybYunPayDTO dto) throws Exception {
        String url = SYB_YUN_PAY_API + YUN_PAY_PATH;
        TreeMap<String, String> params = SybUtil.parseEntity(dto);
        Map<String, String> map = doPay(url, params);
        map.put("result", "0000");
        return map;
    }

    public static Map<String, String> wxPay(SybWxPayDTO dto) throws Exception {
        String url = SYB_APIURL + PAY_PATH;
        TreeMap<String, String> params = SybUtil.parseEntity(dto);
        Map<String, String> map = doPay(url, params);
        map.put("result", "0000");
        return map;
    }

    public static Map<String, String> doPay(String url, TreeMap<String, String> params) throws Exception {
        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String, String> multiParams = SybPayUtils.convert(params);
        StringBuilder builder = new StringBuilder();
        builder.append("\n").append("请求地址: POST ").append(url);
        builder.append("\n").append("请求参数:").append(JSONUtil.toJsonPrettyStr(params));
        // 请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(multiParams, headers);
        ResponseEntity<String> response = restTemplate.exchange(
                url,
                HttpMethod.POST,
                requestEntity,
                String.class
        );
        String responseBody = response.getBody();
        builder.append("\n").append("响应结果:").append(JSONUtil.toJsonPrettyStr(responseBody));
        LogUtils.info(builder.toString());
        return JSONUtil.toBean(responseBody, Map.class);
    }
}
